<template>
  <HeaderComponent />
  <div style="background-color: #e4e7ed;min-height: 100vh;">
    <div class="follow-container">
      <!--搜索框-->
      <div class="search-section">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户"
          clearable
          class="search-input"
          @input="searchUsers"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <el-tabs v-model="activeTab" class="follow-tabs">
        <!-- 全部用户标签页 -->
        <el-tab-pane label="全部用户" name="all">
          <UserList
            :users="filteredAllUsers"
            :is-followed="isFollowed"
            @follow="handleFollow"
            @unfollow="handleUnfollow" 
          />
        </el-tab-pane>
        <!-- 已关注标签页 -->
        <el-tab-pane label="已关注" name="following">
          <UserList
            :users="filteredFollowingUsers"
            :is-followed="() => true"
            @unfollow="handleUnfollow"
          />
        </el-tab-pane>
        <!-- 被关注标签页-->
        <el-tab-pane label="被关注" name="followers">
          <UserList
            :users="filteredFollowersUsers"
            :is-followed="isFollowed"
            :hide-actions="true" 
          />
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import HeaderComponent from "../../components/HeaderComponent.vue";
import UserList from "../../components/UserList.vue";
import { Search } from "@element-plus/icons-vue";
import api from "../../utils/index.js";
import userStore from "../../store/index";
import { ElMessage } from "element-plus";

const userStoreInfo = userStore();
const currentUser = userStoreInfo.getUser();
const searchQuery = ref("");
const activeTab = ref("all");
const allUsers = ref([]);
const followingUsers = ref([]);
const followersUsers = ref([]); 

// 获取所有用户
const fetchAllUsers = async () => {
  try {
    const response = await api.get("/users");
    allUsers.value = response.data.filter((user) => user.id !== currentUser.id);
  } catch (error) {
    ElMessage.error("获取用户列表失败");
  }
};

// 获取已关注用户
const fetchFollowingUsers = async () => {
  try {
    const response = await api.get(`/users?id=${currentUser.id}`);
    const followingIds = response.data[0].contact || [];

    const promises = followingIds.map((id) => api.get(`/users?id=${id}`));
    const results = await Promise.all(promises);

    followingUsers.value = results.map((res) => res.data[0]);
  } catch (error) {
    ElMessage.error("获取关注列表失败");
  }
};

// 获取被关注用户（关注我的用户）
const fetchFollowersUsers = async () => {
  try {
    const response = await api.get("/users");
    followersUsers.value = response.data.filter(
      (user) => user.contact && user.contact.includes(currentUser.id)
    );
  } catch (error) {
    ElMessage.error("获取被关注列表失败");
  }
};

// 搜索过滤被关注用户
const filteredFollowersUsers = computed(() => {
  return followersUsers.value.filter((user) =>
    user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});



// 检查是否已关注
const isFollowed = (userId) => {
  return followingUsers.value.some((user) => user.id === userId);
};
// 处理关注
const handleFollow = async (userId) => {
  try {
    const UserContact = await api.get(`/users/${currentUser.id}`);
    await api.patch(`/users/${currentUser.id}`, {
      contact: [...(UserContact.data.contact || []), userId],
    });
    ElMessage.success("关注成功");
    fetchFollowingUsers();
  } catch (error) {
    ElMessage.error("关注失败");
  }
};

// 处理取消关注
const handleUnfollow = async (userId) => {
  try {
    const UserContact = await api.get(`/users/${currentUser.id}`);
    await api.patch(`/users/${currentUser.id}`, {
      contact: (UserContact.data.contact || []).filter((id) => id !== userId),
    });
    ElMessage.success("已取消关注");
    fetchFollowingUsers();
  } catch (error) {
    ElMessage.error("取消关注失败");
  }
};

// 搜索过滤
const filteredAllUsers = computed(() => {
  return allUsers.value.filter((user) =>
    user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

const filteredFollowingUsers = computed(() => {
  return followingUsers.value.filter((user) =>
    user.username.toLowerCase().includes(searchQuery.value.toLowerCase())
  );
});

onMounted(() => {
  fetchAllUsers();
  fetchFollowingUsers();
  fetchFollowersUsers(); // 新增
});
</script>

<style>
.follow-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.search-section {
  margin-bottom: 20px;
}

.follow-tabs {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}
.search-input .el-input__wrapper {
  border-radius: 20px;
}
</style>
